import React, { useEffect, useState } from "react";
import { Card, Form, Select, Input, Button, Table } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import type {
  ProvinceList,
  ContentList,
  ContentItem,
  SearchParams,
  ReqHospitalPageType,
} from "@api/hospital/model/hospitalListType";
import {
  reqGetProvinceListApi,
  reqGetCityListOrDistrictListApi,
  reqGetHospitalPageListApi,
  reqUpdateHospitalStatusApi,
} from "@api/hospital";
import { useNavigate } from "react-router-dom";

const { Option } = Select;

let flag = false;

export default function HospitalList() {
  const [form] = Form.useForm();
  const navigate = useNavigate();

  // 省级列表
  const [provinceList, setProvinceList] = useState<ProvinceList>([]);
  // 市级列表
  const [cityList, setCityList] = useState<ProvinceList>([]);
  // 区级列表
  const [districtList, setDistrictList] = useState<ProvinceList>([]);
  // 医院类型列表
  const [hospitalTypeList, setHospitalTypeList] = useState<ProvinceList>([]);
  // 分页医院列表
  const [hospitalList, setHospitalList] = useState<ContentList>([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(0);

  // 表格的loading效果
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // 获取省级列表
    getProvinceList();
    // 获取医院类型列表
    getHospitalTypeList();
    // 获取分页医院列表
    getHospitalPageList(page, pageSize);
  }, []);

  // 条件查询
  function onFinish(params: SearchParams) {
    flag = true;
    getHospitalPageList(page, pageSize);
  }

  // 上线/下线
  function updaeHospitalStatus(id: number, status: number) {
    return async () => {
      if (status) {
        await reqUpdateHospitalStatusApi(id, 0);
      } else {
        await reqUpdateHospitalStatusApi(id, 1);
      }
      getHospitalPageList(page, pageSize);
    };
  }

  // 获取分页医院列表
  async function getHospitalPageList(page: number, pageSize: number) {
    setLoading(true);
    let res;
    if (!flag) {
      res = await reqGetHospitalPageListApi(page, pageSize);
    } else {
      // 带搜索条件
      const params = form.getFieldsValue();
      res = await reqGetHospitalPageListApi(page, pageSize, params);
    }
    setHospitalList((res as ReqHospitalPageType).content);
    setTotal((res as ReqHospitalPageType).totalElements);
    setLoading(false);
  }

  // 获取省列表
  async function getProvinceList() {
    const res = await reqGetProvinceListApi();
    setProvinceList(res);
  }

  // 选中省 获取市列表
  async function ChangeProvince(id: number) {
    const res = await reqGetCityListOrDistrictListApi(id);
    setCityList(res);
    // 清空市、区已选中
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined });
    // 清空区下拉列表
    setDistrictList([]);
  }

  // 选中省 获取区列表
  async function ChangeCity(id: number) {
    const res = await reqGetCityListOrDistrictListApi(id);
    setDistrictList(res);
    form.setFieldsValue({ districtCode: undefined });
  }

  // 获取医院类型列表
  async function getHospitalTypeList() {
    // 获取医院类型（参数固定值为 10000）
    const res = await reqGetCityListOrDistrictListApi(10000);
    setHospitalTypeList(res);
  }

  // 表格结构
  const columns: ColumnsType<ContentItem> = [
    {
      width: 80,
      align: "center",
      title: "序号",
      render: (_, record, index) => index + 1,
    },
    {
      align: "center",
      title: "医院logo",
      dataIndex: "logoData",
      render: (_, record) => (
        <>
          <img
            style={{ height: 80 }}
            src={"data:image/jpeg;base64," + _}
            alt="logo"
          />
        </>
      ),
    },
    {
      align: "center",
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      align: "center",
      title: "等级",
      dataIndex: "param",
      render: (_, record) => _.hostypeString,
    },
    {
      align: "center",
      title: "详细地址",
      dataIndex: "param",
      render: (_, record) => _.fullAddress,
    },
    {
      align: "center",
      title: "状态",
      dataIndex: "status",
      render: (_, record) => (_ === 1 ? "已上线" : "未上线"),
    },
    {
      align: "center",
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      align: "center",
      width: 250,
      fixed: "right",
      title: "操作",
      render: (_, record) => (
        <>
          <Button
            type="primary"
            htmlType="submit"
            onClick={() => {
              navigate(`/syt/hospital/hospitallist/detail/${record.id}`);
            }}
          >
            查看
          </Button>
          <Button
            type="primary"
            style={{ marginLeft: 10, marginRight: 10 }}
            onClick={() => {
              navigate(`/syt/hospital/hospitallist/schedlue/${record.hoscode}`);
            }}
          >
            排班
          </Button>
          <Button
            type="primary"
            onClick={updaeHospitalStatus(record.id, record.status)}
          >{`${record.status === 0 ? "上线" : "下线"}`}</Button>
        </>
      ),
    },
  ];

  return (
    <Card>
      <Form form={form} onFinish={onFinish} layout="inline">
        <Form.Item name={"provinceCode"}>
          <Select
            placeholder={"请选择省"}
            style={{ width: 200 }}
            onChange={ChangeProvince}
          >
            {provinceList.map((provinceItem) => {
              return (
                <Option value={provinceItem.value} key={provinceItem.id}>
                  {provinceItem.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name={"cityCode"}>
          <Select
            placeholder={"请选择市"}
            style={{ width: 200 }}
            onChange={ChangeCity}
          >
            {cityList.map((cityItem) => {
              return (
                <Option value={cityItem.value} key={cityItem.id}>
                  {cityItem.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name={"districtCode"}>
          <Select
            placeholder={"请选择区"}
            style={{ width: 200, marginBottom: 20 }}
          >
            {districtList.map((districtItem) => {
              return (
                <Option value={districtItem.value} key={districtItem.id}>
                  {districtItem.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name={"hosname"}>
          <Input placeholder="医院名称" style={{ width: 200 }} />
        </Form.Item>
        <Form.Item name={"hoscode"}>
          <Input placeholder="医院编号" style={{ width: 200 }} />
        </Form.Item>
        <Form.Item name={"hostype"}>
          <Select placeholder={"医院类型"} style={{ width: 200 }}>
            {hospitalTypeList.map((hospitalTypeItem) => {
              return (
                <Option
                  value={hospitalTypeItem.value}
                  key={hospitalTypeItem.id}
                >
                  {hospitalTypeItem.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name={"status"}>
          <Select placeholder={"医院状态"} style={{ width: 200 }}>
            <Option value={1}>上线</Option>
            <Option value={0}>下线</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button
            onClick={() => {
              flag = false;
              form.resetFields();
              getHospitalPageList(1, pageSize);
            }}
          >
            清空
          </Button>
        </Form.Item>
      </Form>
      <Table
        loading={loading}
        style={{ marginTop: 20 }}
        scroll={{ x: 1300 }}
        bordered
        columns={columns}
        dataSource={hospitalList}
        rowKey={"id"}
        pagination={{
          current: page,
          total,
          pageSize,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 15],
          showTotal(total, range) {
            return `总共： ${total} 条`;
          },
          onChange(page, pageSize) {
            // 请求新的数据之前，清空之前的数据，解决每页显示条数由多变少切换时控制台报错
            setHospitalList([]);
            getHospitalPageList(page, pageSize);
            setPage(page);
            setPageSize(pageSize);
          },
        }}
      />
    </Card>
  );
}
